// src/stores/models/AuthStore.ts
import { types, flow, Instance } from "mobx-state-tree";

// 认证存储模型
export const AuthStore = types
  .model("AuthStore", {
    token: types.maybe(types.string),
    userId: types.maybe(types.string),
    isLoading: false,
    error: types.maybe(types.string),
    email: types.optional(types.string, ""),
    password: types.optional(types.string, ""),
  })
  .actions((self) => ({
    login: flow(function* (email: string, password: string) {
      self.isLoading = true;
      self.error = undefined;
      
      try {
        // 模拟API调用
        yield new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟登录成功
        self.token = "sample-jwt-token";
        self.userId = "user-123";
        self.isLoading = false;
        return { success: true };
      } catch (error: any) {
        self.isLoading = false;
        self.error = error.message;
        return { success: false, error: error.message };
      }
    }),
    
    logout: () => {
      self.token = undefined;
      self.userId = undefined;
    },
    
    setError: (error: string) => {
      self.error = error;
    },
    
    setEmail: (email: string) => {
      self.email = email;
    },
    
    setPassword: (password: string) => {
      self.password = password;
    },
  }))
  .views((self) => ({
    get isAuthenticated() {
      return !!self.token;
    },
  }));

export type AuthStoreInstance = Instance<typeof AuthStore>;